<template>
<div>
	<!--预览/下载附件dialog-->
	<el-dialog title='文件操作' :visible.sync="fileOptVisible" :fullscreen="fullscreen">
		<div slot="title">
	    <span class="title-text">{{file.name}}</span>
	    <el-button type="text" size="mini"><i class="fa fa-download"></i> <a :href="file.url" download>下载</a></el-button>
	    <button type="button" class="el-fullscreen" @click="fullScreen"><i :class="screenIcon"></i></button>
	  </div>
	  <div class="pdfTitle" v-if="previewType=='pdf'">
	    <el-button size="small" @click="changePdfPage(0)">上一页</el-button>
	    <span>{{currentPage}}/{{pageCount}}</span>
	    <el-button size="small" @click="changePdfPage(1)">下一页</el-button>
			<pdf
				:src="file.url"
				:page="currentPage"
				@num-pages="pageCount=$event"
				@page-loaded="currentPage=$event">
			</pdf>
		</div>

		<el-image
			v-if="previewType=='image'"
			style="width: 100%;"
    	:src="file.url">
  	</el-image>
	</el-dialog>

	<!---上传附件dialog-->
	<el-dialog title="上传附件" :visible.sync="uploadVisible" :fullscreen="fullscreen">
		<div slot="title">
	    <span class="title-text">上传附件</span>
	    <button type="button" class="el-fullscreen" @click="fullScreen"><i :class="screenIcon"></i></button>
	  </div>
	  <el-upload
    	multiple
    	:data="data"
    	:headers="headers"
    	:before-upload="beforeUpload"
    	:before-remove="removeFile"
		  class="upload-demo"
		  :action="upload_url"
		  :on-success="upSuccess"
		  :file-list="event.attach">
		  <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
		</el-upload>
	</el-dialog>

	<el-dialog :title="action+'办理'" :visible.sync="logAddVisible">
		<el-form>
			<el-form-item label="标题" label-width="80px">
				<el-input v-model="form.title"></el-input>
			</el-form-item>
			<el-form-item label="内容" label-width="80px">
				<el-input type="textarea" :autosize="{ minRows: 5, maxRows: 20}" v-model="form.content"></el-input>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
	    <el-button @click="logAddVisible = false">取 消</el-button>
		    <el-button type="primary" @click="save">确 定</el-button>
		  </div>
	</el-dialog>

	<!--数据列表展示-->
	<div>
		<span style="font-weight: 500;">项目基本详情</span>
		<el-row style="padding: 10px;">
			<el-col :span=8 v-for="(field,index) in fields" :key="index">
				<span class="info-name">{{field.ch_name}}:</span>
				<span v-if="field.type_name=='日期'">{{formatTime(project[field.en_name])}}</span>
		  		<span v-else-if="urlJudge(project[field.en_name])" class="attach-display">
		  			<span v-for="(item,index) in project[field.en_name]" class="file-link ">
		  				<div @click="fileOpt(item)" style="cursor: pointer;">{{item.name}}</div>
		  			</span>
		  		</span>
		  		<span v-else-if="listJudge(project[field.en_name])">
		  			<el-tag
		  				style="margin-right: 2px;"
		  				v-for="(member,index) in project[field.en_name]"
		  				type="success"
		  				:key="index"
		  				size="small">
		  				{{member}}
		  			</el-tag>
		  		</span>
        <span v-else>{{project[field.en_name]}}</span>
			</el-col>
		</el-row>

		<div style="margin-top: 40px;">
			<span style="font-weight: 500;">项目办理记录</span>

			<el-button icon="el-icon-plus" size="mini" type="primary" @click="add">添加</el-button>
			<el-button icon="el-icon-search" size="mini" type="primary" @click="search">搜索</el-button>
			
			<el-row style="padding:10px;">
				<el-col :lg="8" style="margin-bottom: 10px;">
					<div class="search-key">标题: </div>
					<el-input size="mini" style="width: 400px;" v-model="searchData.title"></el-input>
				</el-col>
				<el-col :lg="8" style="margin-bottom: 10px;">
					<div class="search-key">内容: </div>
					<el-input size="mini" style="width: 400px;" v-model="searchData.content"></el-input>
				</el-col>
				<el-col :lg="8" style="margin-bottom: 10px;">
					<div class="search-key">附件: </div>
					<el-input size="mini" style="width: 400px;" v-model="searchData.attach"></el-input>
				</el-col>
				
			</el-row>

			<el-table :data="events" border>
				<el-table-column
	        prop="title"
	        label="标题">
	      </el-table-column>
	      <el-table-column
	        prop="content"
	        label="内容">
	        <template slot-scope="scope">
	        	<div class="pre-line">{{scope.row.content}}</div>
	        </template>
	      </el-table-column>
	      <el-table-column
	        prop="create_time"
	        label="创建时间"
	        width="180">
	        <template slot-scope="scope">
	        	<span>{{formatTime(scope.row.create_time)}}</span>
	        </template>
	      </el-table-column>
	      <el-table-column
	        prop="update_time"
	        label="更新时间"
	        width="180">
	        <template slot-scope="scope">
	        	<span>{{formatTime(scope.row.update_time)}}</span>
	        </template>
	      </el-table-column>
	      <el-table-column
	        prop="attach"
	        label="附件">
	        <template slot-scope="scope">
	        	<div v-for="(item,index) in scope.row.attach" class="file-link">
		  				<span @click="fileOpt(item)" style="cursor: pointer;">{{item.name}}</span>
		  			</div>
	        </template>
	      </el-table-column>
	      <el-table-column
	      	fixed="right"
	        label="操作">
	        <template slot-scope="scope">
	        	<el-button size="mini" icon="el-icon-edit" type="primary" title="编辑" @click="edit(scope.row)"></el-button>
	      		<el-button size="mini" icon="el-icon-delete" type="danger" title="删除" @click="del(scope.row)"></el-button>
	      		<el-button size="mini" icon="el-icon-upload" type="success" title="上传附件" @click="upload(scope.row)"></el-button>
	        </template>
	      </el-table-column>
			</el-table>
		</div>
		
	</div>
</div>
</template>
<script>
import {getAPItokenRes,postAPItoken,putAPItoken,deleteAPItoken} from '@/utils/api'
import Upload from './upload'
import Member from './member'
import pdf from 'vue-pdf'
export default {
	components: {
		Upload,
		Member,
		pdf
	},
	data () {
		return {
			previewType: null,
			currentPage: 1, // pdf文件页码
      pageCount: 0, // pdf文件总页数
			file: {},
			fullscreen: false,
			screenIcon: 'fa fa-expand',
			action: '添加',
			form: {}, // 添加事件form
			fileOptVisible:  false,
			uploadVisible: false,
			fields: [], // 字段列表
			project: {}, // 项目对象
			downClass: 'fa fa-angle-double-up',
			searchData: {},
			logAddVisible: false, // 事件添加dialog
			events: [], // 事件列表
			upload_url:API.eventAttach,
			headers: {
        'Authorization': 'Token ' + this.$store.state.user.token
      },
      data: {}, // 上传附件额外数据,
      event: {}, // 当前操作的事件
		}
	},
	methods: {
		add () {
			this.action = '添加'
			this.logAddVisible = true
		},
		edit (evt) {
			this.form = evt
			this.action = '编辑'
			this.logAddVisible = true
		},
		del (evt) {
			this.event = evt
			this.$confirm('删除事件:'+this.event.title+', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      	this.executeDel()
      }).catch(() => {})
		},
		executeDel () {
    	const promise = deleteAPItoken(API.proEvent+this.event.id+'/',this.token)
    	promise.then((res)=>{
    		if (res.status == 204){
    			this.$notify({
	          type: 'success',
	          message: '删除成功!'
	        })
    		}
    		this.getProEvents()
    	})
    },
		upload (evt) {
			this.event = evt
			this.uploadVisible = true
		},
		search () {
			const promise = postAPItoken(API.eventSearch,{'search':this.searchData,'project':this.project.id},this.token)
			promise.then((data)=>{
				this.events = data
			})
		},
		getFields () {
      const promise = getAPItokenRes(API.tempField+'?template='+this.$route.query.template,this.token)
      promise.then((res)=>{
        if (res.status == 200) {
        	this.fields = res.data
        	this.getProject()
        }
      })
    },
    getProject () {
      const promise = getAPItokenRes(API.instAPI+this.$route.query.project+'/',this.token)
      promise.then((res)=>{
        if (res.data.status) {
        	this.project = res.data.data
        	this.getProEvents()
        }
      })
    },
    getProEvents () {
    	const promise = getAPItokenRes(API.proEvent+'?project='+this.project.id,this.token)
    	promise.then(res=>{
    		if(res.status == 200){
    			this.events = res.data
    		}
    	})
    },
    save () {
    	this.form['project'] = this.project.id
    	if (this.action == '添加') {
    		var promise = postAPItoken(API.proEvent,this.form,this.token)
    	} else {
    		var promise = putAPItoken(API.proEvent+this.form.id+'/',this.form,this.token)
    	}
    	promise.then((res)=>{
    		if(res.status){
    			this.$notify({
		        title: '成功',
		        message: '事件:'+this.form.title+', '+this.action+'成功',
		        type: 'success'
		      })
		      this.getProEvents()
    		}else{
    			this.$notify({
		        title: '失败',
		        message: res.data,
		        type: 'error'
		      })
    		}
    	})
    },
    fullScreen () {
    	if (this.fullscreen){
				this.fullscreen = false
				this.screenIcon = 'fa fa-expand'
    	}else{
    		this.fullscreen = true
    		this.screenIcon = 'fa fa-compress'
    	}
    },
    listJudge (field_val) {
    	if (field_val instanceof Array){
    		return true
    	}else{
    		return false
    	}
    },
    urlJudge (field_val) {
    	if (field_val instanceof Array && field_val[0] instanceof Object){
    		return true
    	}else{
    		return false
    	}
    },
    fileOpt (item) {
    	//this.file.src = pdf.createLoadingTask(item.url)
    	if (item.name.endsWith('pdf')){
    		this.previewType = 'pdf'
    	}else{
    		this.previewType = 'image'
    	}
    	this.file = item
    	this.fileOptVisible = true
    },
    changePdfPage (val) {
      // console.log(val)
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--
        // console.log(this.currentPage)
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++
        // console.log(this.currentPage)
      }
    },
    FormatTime(time,fmt){
		  var o = {
	      "M+": time.getMonth() + 1, //月份 
	      "d+": time.getDate(), //日 
	      "H+": time.getHours(), //小时 
	      "m+": time.getMinutes(), //分 
	      "s+": time.getSeconds(), //秒 
	      "q+": Math.floor((time.getMonth() + 3) / 3), //季度 
	      "S": time.getMilliseconds() //毫秒 
		  }
		  if (/(y+)/.test(fmt))
		  	fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length))
		  for (var k in o)
		  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
		  return fmt
		},
		formatTime (date_string) {
			try {
    		var s1 = date_string.replace(/-/g,"/")
    		var s2 = s1.replace(/T/g," ")
				var date = new Date(s2)
				return this.FormatTime(date, 'yyyy-MM-dd HH:mm:ss')
			}
			catch(err) {}
		},
		handlePreview (file) {
			this.dialogImageUrl = file.url
  		this.dialogVisible = true
		},
		upSuccess (response, file, fileList) {
			file['id'] = response.id
			this.getProEvents()
		},
		delFile (id,fileList) {
			const promise = deleteAPItoken(API.eventAttach+id+'/',this.$store.state.user.token)
			promise.then((res)=>{
				if (res.status) {
					fileList.forEach((v,i)=>{
						if(v.id==id){
							fileList.splice(i,1)
						}
					})
					this.$message({
            type: 'success',
            message: '删除成功!'
          })
				} else {
					this.$message({
            type: 'error',
            message: '删除失败!, '+res.data
          })
				}
			})
		},
		removeFile (file,fileList) {
			if (file.status === 'success'){
				this.$confirm('删除'+file.name+', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        	this.delFile(file.id,fileList)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
          return false    
        })
      } 
			return false
		},
		beforeUpload (file,fileList) {
			this.data['project'] = this.project.id
			this.data['event'] = this.event.id
			this.data['attach'] = file
		},
	},
	mounted () {
		this.token = this.$store.state.user.token
		this.getFields()
	}
}
</script>
<style scoped>
.search-key {
	color: #7a838f;
	font-size: 14px;
}
.el-button--mini, .el-button--mini.is-round {
  padding: 7px 7px;
}
.el-fullscreen {
  position: absolute;
  top: 20px;
  right: 40px;
  padding: 0;
  background: 0 0;
  border: none;
  outline: 0;
  cursor: pointer;
  font-size: 12px;
}
a {
	text-decoration:none;
	color: #409eff;
}

.file-link{
	overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

span{
	font-weight: 300;
}

.info-name {
	color:#7a838f;
	width: 100px;
	display: inline-block;
	text-align: right;
	margin-right: 10px;
	vertical-align:top;
}
.attach-display{
	display: inline-block;
	width: 70%;
	overflow: hidden;
	white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align:top;
}

.pre-line {
  white-space: pre-line;
}
</style>